<?php
class SP_Controller_Module
{
	protected $_route_vars = array();
	protected $_vars = array();
	protected $_page;
	protected $_view;
	protected $_config;
	protected $_path;
	protected $_action;
	
	public function __construct($path)
	{
		$this->_path=$path;
		$this->_config = new SP_Config_Configuration($path.SP_Config::get('system_app')->module_config_name);
	}
	
	public function setPage($value)
	{
		$this->_page=$value;
	}
	
	public function getPath()
	{
		return $this->_path;
	}
	
	public function getConfig()
	{
		return $this->_config;
	}
	
	public function setRouteVars($value)
	{
		$this->_route_vars=$value;
	}
	
	public function getRouteVar($name,$value=null)
	{
		return $this->hasRouteVar($name)? $this->_route_vars[$name] : $value;
	}
	
	public function getRouteVars()
	{
		return $this->_route_vars;
	}
	
	public function _GET($name, $value=null)
	{
		return $this->getRouteVar($name, $value);
	}
	
	public function setRouteVar($name,$value)
	{
		$this->_route_vars[$name]=$value;
	}
	
	public function hasRouteVar($name)
	{
		return array_key_exists($name, $this->_route_vars);
	}
	
	public function getVars()
	{
		return $this->_vars;
	}
	
	public function set($name,$value)
	{
		$this->_vars[$name]=$value;
	}
	
	public function has($name)
	{
		return array_key_exists($name, $this->_vars);
	}
	
	public function get($name,$value=null)
	{
		return $this->has($name)? $this->_vars[$name] : $value;
	}
	
	public function __set($name,$value)
	{
		$this->set($name,$value);
	}
	
	public function __get($name)
	{
		return $this->get($name);
	}
	
	public function hasAction($name)
	{
		return method_exists($this, 'start'.$name);
	}
	
	public function setView($name)
	{
		$this->_view=$name;
	}
	
	public function getView()
	{
		return $this->_view;
	}
	
	public function getViewFile()
	{
		$view = $this->getView()? $this->getView() : $this->getAction();
		return $this->getPath().$view.'.php';
	}

	public function setAction($name)
	{
		$this->_action=$name;
	}
	
	public function getAction()
	{
		return $this->_action;
	}

	public function execute($action=null)
	{
		if( !$action ) $action=$this->_action;
		if( $this->hasAction($action) )
		{
			$name='start'.$action;
			if( method_exists($this, 'beforeStart') ) $this->beforeStart($this->_page);
			$this->$name($this->_page);
			if( method_exists($this, 'afterStart') ) $this->afterStart($this->_page);
		}
		else
		{
			throw new Exception('Action "'.$action.'" not found');
		}
	}
}